<template>
  <div class="el-row--flex user-content h-100">
    <div class="header el-row--flex flex-between p-2">
      <div class="left">
        <el-input
          size="small"
          v-model="query.keyword"
          placeholder="请输入用户名/账号"
        >
          <template slot="append">
            <el-button
              size="mini"
              @click="search">搜索</el-button>
          </template>
        </el-input>
      </div>
      <div class="right">
        <el-button
          type="primary"
          size="small"
          @click="addUser"
        >添加用户
        </el-button>
<!--        <el-button-->
<!--          size="small"-->
<!--          @click="delList"-->
<!--        >删除-->
<!--        </el-button>-->
      </div>
    </div>
    <div class="content flex-1 p-l-2 p-r-2">
      <el-table
        :data="tableData"
        height="100%"
        border
        @selection-change="selectChange"
      >
<!--        表格多选列-->
<!--        <el-table-column-->
<!--          type="selection"-->
<!--        />-->
        <el-table-column
          prop="UserID"
          label="用户编号"
        />
        <el-table-column
          prop="UserName"
          label="用户名"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="showUser(scope.row)">{{ scope.row.UserName }}</el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="UserAccount"
          label="账号"
        />
        <el-table-column
          prop="UserVip"
          label="是否Vip"
        />
        <el-table-column
          label="操作"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="edit(scope.row)">编辑</el-button>
            <el-button type="text" @click="del(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
<!--    查看用户详情的抽屉-->
    <el-drawer
      class="user-drawer"
      size="500px"
      :visible.sync="visible"
      :title="eyeUser.UserName"
    >
      <table class="m-2 user-table">
<!--        <tr>-->
<!--          <td class="text-left">用户头像：</td>-->
<!--          <td class="m-r">-->
<!--            <el-image style="width: 60px;height: 60px;display: inline;" :src="eyeUser.head"/>-->
<!--          </td>-->
<!--        </tr>-->
        <tr>
          <td class="text-left" style="width: 100px">用户名：</td>
          <td>{{ eyeUser.UserName }}</td>
        </tr>
        <tr>
          <td class="text-left">账号：</td>
          <td>{{eyeUser.UserAccount}}</td>
        </tr>
        <tr>
          <td class="text-left">角色：</td>
          <td>
              {{getUserRole(eyeUser)}}
          </td>
        </tr>
      </table>
    </el-drawer>
<!--    添加、编辑用户信息的dialog弹窗-->
    <el-dialog
      :title="dialogType === 'add' ? '添加用户' : dialogType === 'edit' ? '编辑用户' : ''"
      :visible.sync="dialogVisible"
      width="450px"
      @close="dialogUser = {user_role:[]};dialogRole = []"
    >
      <el-form
        v-model="dialogUser"
      >
        <el-form-item
          label="用户名"
        >
          <el-input v-model="dialogUser.UserName"/>
        </el-form-item>
        <el-form-item
          label="账号"
        >
          <el-input v-model="dialogUser.UserAccount"/>
        </el-form-item>
        <el-form-item
          label="密码"
        >
          <el-input v-model="dialogUser.UserPwd"/>
        </el-form-item>
        <el-form-item
          label="是否Vip"
        >
          <el-radio-group
            v-model="dialogUser.UserVip"
          >
            <el-radio label="是"/>
            <el-radio label="否"/>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="角色"
        >
          <el-select
            v-model="dialogRole"
            multiple
          >
            <el-option
              v-for="(item,index) in roles"
              :key="index"
              :label="item.name"
              :value="item.roleId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button
          type="primary"
          size="small"
          @click="submit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {mapState} from 'vuex'

export default {
  name: "user",
  layout: 'base',
  data() {
    return {
      tableData: [],
      query: {
        keyword: '',
      },
      selectItem: [],
      visible:false,
      eyeUser:{}, //当前查看的用户信息
      dialogVisible:false, //添加、编辑用户信息的弹窗
      dialogUser:{
        user_role:[]
      }, //添加、编辑用户的表单数据对象
      dialogRole:[],
      dialogType:'add'
    }
  },
  computed:mapState({
    roles:state => state.user.roles
  }),
  methods: {
    /**
     * 显示用户信息
     * @param val
     */
    showUser(val) {
      this.visible = true
      this.eyeUser = val
    },
    /**
     * 列表 操作 编辑按钮点击事件
     * @param val
     */
    edit(val) {
      this.$axios.$get('http://localhost:8001/user/getUserById?userId='+val.UserID)
      .then(res => {
        this.dialogUser = res.user
        this.dialogRole = res.roles
      })
      .catch(error => {
        this.$message.error('获取用户信息失败！')
        console.log(error)
        this.dialogVisible = false //关闭弹窗
      })
      this.dialogType = 'edit'
      this.dialogVisible = true
    },
    /**
     * 列表 操作 删除按钮点击事件
     * @param val
     */
    del(val) {
      this.$confirm(`确认删除 - ${val.UserName}?`, '提示')
        .then(() => {
          //执行删除逻辑
          this.$axios.$get('http://localhost:8001/user/deleteUser?userIds=' + val.UserID)
            .then(res => {
              if (res.state) {
                //调用搜索方法，刷新表格数据
                this.search()
              } else {
                this.$message.error("删除失败")
                console.log(res.message)
              }
            })
            .catch(error => {
              this.$message.error("删除失败，请联系管理员")
              console.log(error)
            })
        })
    },
    /**
     * 批量删除
     */
    delList() {
      if (this.selectItem.length <= 0) {
        this.$message.warning('请选择要删除的用户')
        return
      }
      let users = this.selectItem.map(u => {
        return u.UserName
      })
      this.$confirm(`确认要删除 - ${users.join()} ?`, '警告')
        .then(() => {
          let ids = this.selectItem.map(u => {
            return u.UserID
          })
          this.$axios.$get("http://localhost:8001/user/deleteUser?userIds=" + ids.join())
            .then(res => {
              if (res.state) {
                this.$message.success('删除成功！')
                this.search()
              } else {
                this.$message.error('批量删除失败！')
                console.log(res.message)
              }
            })
            .catch(error => {
              this.$message.error("批量删除失败！")
              console.log(error)
            })
        })
    },
    /**
     * 搜索按钮点击事件
     */
    search() {
      this.$axios.$get('http://localhost:8001/user/search?keywork=' + this.query.keyword)
        .then(res => {
          this.tableData = res
        })
        .catch(error => {
          this.$message.error('系统异常，请联系管理员')
          console.log(error)
        })
    },
    /**
     * 添加按钮点击事件
     */
    addUser() {
      this.dialogType = 'add'
      this.dialogVisible = true
    },
    /**
     * 表格多选项变化
     * @param selectList
     */
    selectChange(selectList) {
      this.selectItem = selectList
    },
    getUserRole(user){
      if(user && user.user_role){
        let roles = user.user_role.map(u => {
          return u.role.name
        })
        return roles.join()
      }
      return ''
    },
    submit(){
      console.log(this.dialogUser)
      if(this.dialogType === 'add'){
        this.$axios.$post('http://localhost:8001/user/addUser',{user:this.dialogUser,roles:this.dialogRole})
        .then(res => {
          if(res.state){
            this.$message.success('添加成功！')
            this.search() //刷新列表
          }else{
            this.$message.error("添加失败！")
            console.log(res.message)
          }
        })
        .catch(error => {
          this.$message.error('添加失败！')
          console.log(error)
        })
        .finally(() => {
          this.dialogVisible = false
        })
      }else if(this.dialogType === 'edit'){
        this.$axios.$post('http://localhost:8001/user/editUser',{user:this.dialogUser,roles:this.dialogRole})
          .then(res => {
            if(res.state){
              this.$message.success('编辑成功！')
              this.search() //刷新列表
            }else{
              this.$message.error("编辑失败！")
              console.log(res.message)
            }
          })
          .catch(error => {
            this.$message.error('编辑失败！')
            console.log(error)
          })
          .finally(() => {
            this.dialogVisible = false
          })
      }
    }
  },
  created() {
    //初始化表格数据
    this.$axios.$get('http://localhost:8001/user/getUserAll')
      .then(res => {
        this.tableData = res
      })
      .catch(error => {
        this.$message.error('表格数据初始化失败')
        console.log(error) //将错误信息打印到控制台
      })
    if(this.roles === null || this.roles.length <=0){
      this.$axios.$get('http://localhost:8001/role/getAllrole')
      .then(res => {
        this.$store.commit('user/setRoles',res)
      })
      .catch(error => {
        this.$message.error('角色信息获取失败')
        console.log(error)
      })
    }
  }
}
</script>

<style lang="less">
.user-content {
  flex-direction: column;
  .content{
    height: 1px;
  }
  .user-drawer{
    tr{
      line-height: 60px;
    }
  }
}
</style>
